package com.itheima.task;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/*
* 写一个方法，此方法可以获取obj对象中名为propertyName的属性的值
	public Object getProperty(Object obj, String propertyName){

	}
* */
public class Demo5 {
    public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        PersonDemo5 personDemo5 = new PersonDemo5("1","李四",18,true);
        System.out.println(personDemo5);
        Object propertyName = getProperty(personDemo5, "propertyAge");
        System.out.println(propertyName);


    }

    private static Object getProperty(Object obj,String propertyName) throws IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {
        Class clazz = obj.getClass();
        Field propertyName1 = clazz.getDeclaredField("propertyName");
        Class type = propertyName1.getType();
        String methodName ="";
        if (type==boolean.class){
            methodName="is"+propertyName.substring(0,1).toUpperCase()+propertyName.substring(1);
        }else{
            methodName="get"+propertyName.substring(0,1).toUpperCase()+propertyName.substring(1);
        }
        Method method = clazz.getMethod(methodName);
        Object invoke = method.invoke(obj);
        return invoke;

    }
    /*public static Field getProperty(Object obj) throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class clazz = obj.getClass();
        Object o = clazz.newInstance();
        Field declaredField = clazz.getDeclaredField("propertyName");
        declaredField.setAccessible(true);
        declaredField.set(o,"李四");
        Properties properties = new Properties();
        return declaredField;
    }*/
}
